package cn.schoolwow.quickdao.module.database.dml.instance.flow.insert.common;

import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.module.database.dml.instance.flow.insert.get.GetUniqueKeyValueListFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;

import java.util.List;
import java.util.Set;

public class DistinguishByUniqueKeyFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        flowContext.executeFlowList(new GetUniqueKeyValueListFlow());
        addExistInstanceSet(flowContext);
    }

    @Override
    public String name() {
        return "根据唯一约束字段判断实例是否存在";
    }

    private void addExistInstanceSet(FlowContext flowContext){
        Object[] instances = (Object[]) flowContext.checkData("instances");
        Set<Object> existInstanceSet = (Set<Object>) flowContext.getData("existInstanceSet");
        List<Property> uniquePropertyList = flowContext.checkData("uniquePropertyList", List.class);
        List<String> uniqueKeyValueList = (List<String>) flowContext.getData("uniqueKeyValueList");

        StringBuilder uniqueFieldNameValueBuilder = new StringBuilder();
        for(int i=0;i<instances.length;i++){
            uniqueFieldNameValueBuilder.setLength(0);

            Object instance = instances[i];
            for(Property uniqueProperty:uniquePropertyList){
                Object value = QueryInstance.newQuery(instance)
                        .execute()
                        .getSingleFieldValue(uniqueProperty.name);
                if(null==value){
                    throw new IllegalArgumentException("实例唯一字段不能为空!实体类:"+instance.getClass().getName()+",字段名:"+uniqueProperty.name);
                }
                uniqueFieldNameValueBuilder.append(value+"|");
            }
            if(uniqueKeyValueList.contains(uniqueFieldNameValueBuilder.toString())){
                existInstanceSet.add(instance);
            }
        }
    }
}
